package com.hyh.springcloud.controller;

import com.hyh.springcloud.entity.Payment;
import com.hyh.springcloud.lb.LoadBalancer;
import com.hyh.springcloud.result.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author Summerday
 */

@RestController
@Slf4j
public class OrderController {

    //private static final String PAYMENT_URL = "http://localhost:8001";
    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/consumer/payment")
    public AjaxResult create(@RequestBody Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment", payment, AjaxResult.class);
    }

    @GetMapping("/consumer/payment/{id}")
    public AjaxResult getPayment(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/" + id, AjaxResult.class);
    }

    @GetMapping("/consumer/payment/entity/{id}")
    public AjaxResult getPaymentEntity(@PathVariable("id") Long id) {
        ResponseEntity<AjaxResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/" + id, AjaxResult.class);
        log.info(entity.toString());
        if (entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();
        }
        return AjaxResult.error();
    }

    @GetMapping("/consumer/payment/lb")
    public String getPaymentLb() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size() == 0) {
            return null;
        }
        ServiceInstance instance = loadBalancer.instances(instances);
        URI uri = instance.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);

    }

    @GetMapping("/consumer/payment/zipkin")
    public String paymentZipkin(){
        return restTemplate.getForObject("http://localhost:8001" + "/payment/zipkin/",String.class);
    }

}
